package com.jic.point.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.jic.common.base.vo.AdminOperate;
import com.jic.common.base.vo.RestResult;
import com.jic.point.constant.consist.ResponseCode;
import com.jic.point.model.entity.ConfActivityRule;
import com.jic.point.model.entity.ConfActivityRuleApply;
import com.jic.point.model.entity.ConfActivityRuleDetail;
import com.jic.point.model.entity.ConfActivityRuleDetailTemplate;
import com.jic.point.model.vo.request.ConfActivityRuleApplyRequest;
import com.jic.point.model.vo.response.ConfActivityRuleApplyResponse;
import com.jic.point.service.ConfActivityRuleApplyService;
import com.jic.point.service.ConfActivityRuleDetailService;
import com.jic.point.service.ConfActivityRuleService;
import com.jic.point.service.ConfPlatformService;
import com.jic.point.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: tzc
 * @date: 2020-10-11 17:28:32
 */
@RestController
@Slf4j
@RequestMapping("/confActivityRuleApply")
@Api(tags = " [活动规则申请表]控制类-PC")
public class ConfActivityRuleApplyController {
    @Autowired
    private ConfActivityRuleApplyService serviceApply;
    @Autowired
    private ConfActivityRuleService service;
    @Resource
    private ConfActivityRuleDetailService confActivityRuleDetailService;
    @Resource
    private ConfPlatformService confPlatformService;


    /**
     * 新增记录
     *
     * @return ConfActivityRuleApplyResponse 新增[活动规则申请表]响应参数
     * author tzc
     * @date 2020-3-11 20:54:04
     */
    @ApiOperation(value = "新增[活动规则申请表]记录")
    @PostMapping("/save")
    @ResponseBody
    public RestResult<Long> save(@RequestBody Map map) throws Throwable {
        ConfActivityRuleApply confActivityRuleApply = JSON.parseObject(JSON.toJSONString(map.get("dataForm")), ConfActivityRuleApply.class);
        long flag =serviceApply.saveOrUpdate(confActivityRuleApply);
        //组装基本规则表
        Map adminOperate = (Map) map.get("adminOperate");
        List<Map> dataForm2 = (List<Map>) JSONArray.parse(map.get("dataForm2").toString());
        List<Map> ltemp = new ArrayList<>();
        for (Map o : dataForm2) {
            List<Map> list = (List<Map>) o.get("list");
            list.forEach(item -> {
                Map mm = new HashMap();
                mm.put("rulesId", confActivityRuleApply.getId());
                mm.put("templateId", o.get("id"));
                mm.put("sceneName", o.get("sceneName"));
                mm.put("sceneId", o.get("sceneId"));
                mm.put("deptId", Long.parseLong(adminOperate.get("deptId").toString()));
                mm.put("startTime", confActivityRuleApply.getStartTime());
                mm.put("endTime", confActivityRuleApply.getEndTime());
                mm.put("deleteFlag",0);
                mm.put("platformCode",confActivityRuleApply.getPlatformCode());
                for (Object key : item.keySet()) {
                    mm.put(key, item.get(key));
                }
                // ltemp.add(mm);
                //修改
                confActivityRuleDetailService.saveOrUpdate(JSON.parseObject(JSON.toJSONString(mm), ConfActivityRuleDetail.class));
            });
        }
        return RestResult.success(flag);
    }

    /**
     * 新增或修改记录
     *
     * @return ConfActivityRuleApplyResponse 新增或修改[活动规则申请表]响应参数
     * author tzc
     * @date 2020-3-11 20:54:04
     */
    @ApiOperation(value = "保存或更新[活动规则申请表]")
    @PostMapping("/saveOrUpdate")
    @ResponseBody
    @Transactional
    public RestResult<Long> saveOrUpdate(@RequestBody Map map) throws Throwable {
        ConfActivityRuleApply confActivityRuleApply = JSON.parseObject(JSON.toJSONString(map.get("dataForm")), ConfActivityRuleApply.class);
        //组装活动规则主表数据
        Map adminOperate = (Map) map.get("adminOperate");
        confActivityRuleApply.setDeptId(Long.parseLong(adminOperate.get("deptId").toString()));
        confActivityRuleApply.setCode(confActivityRuleApply.getPlatformCode() + DateUtils.format(new Date(), "yyyyMMddHHmmssSSS"));
        confActivityRuleApply.setLimited(confActivityRuleApply.getTotal());
        confActivityRuleApply.setAvailable(confActivityRuleApply.getTotal());
        confActivityRuleApply.setCurrentAction(0);
        confActivityRuleApply.setOutRuleKey("HD" + DateUtils.format(new Date(), "yyyyMMddHHmmssSSS"));
        confActivityRuleApply.setSts(1);
        confActivityRuleApply.setCurrentAction(0);
        confActivityRuleApply.setCreateTime(new Date());
        confActivityRuleApply.setCreator(Long.parseLong(adminOperate.get("operator").toString()));
        confActivityRuleApply.setAdminOperate(JSON.parseObject(JSON.toJSONString(map.get("adminOperate")), AdminOperate.class));
        //插入活动表之前进行积分冻结
        ConfActivityRule confActivityRule = new ConfActivityRule();
        BeanUtils.copyProperties(confActivityRuleApply,confActivityRule);
        int i = confPlatformService.activityRuleDeductionPoints(confActivityRule);
        if (i < 1) return RestResult.error("0111", "生成活动，积分扣除失败！活动添加失败！");
        //积分冻结成功，插入积分表中
        confActivityRule.setType(1);
        service.insertActiveRuleLog(confActivityRule);
        //积分冻结插入平台流水表中delete
        confActivityRule.setType(3);
        confPlatformService.insertPlatFromLog(confActivityRule);
        //插入至活动表
        long flag = serviceApply.saveOrUpdate(confActivityRuleApply);
        //组装基本规则表
        List<Map> dataForm2 = (List<Map>) JSONArray.parse(map.get("dataForm2").toString());
        List<Map> ltemp = new ArrayList<>();
        for (Map o : dataForm2) {
            List<Map> list = (List<Map>) o.get("list");
            list.forEach(item -> {
                Map mm = new HashMap();
                mm.put("rulesCode", confActivityRule.getCode());
                mm.put("templateId", o.get("id"));
                mm.put("sceneName", o.get("sceneName"));
                mm.put("sceneId", o.get("sceneId"));
                mm.put("deptId", Long.parseLong(adminOperate.get("deptId").toString()));
                mm.put("startTime", confActivityRule.getStartTime());
                mm.put("endTime", confActivityRule.getEndTime());
                mm.put("deleteFlag", 0);
                mm.put("platformCode", confActivityRule.getPlatformCode());
                for (Object key : item.keySet()) {
                    mm.put(key, item.get(key));
                }
                ltemp.add(mm);
            });
        }
        //添加规则
        int j = confActivityRuleDetailService.saveListDetail(ltemp);
        return RestResult.success(flag);
    }

    /**
     * 延期申请
     *
     * @param request 申请表延期[活动规则申请表]请求参数
     * @return ConfActivityRuleApplyResponse 删除[活动规则申请表]响应参数
     * author ygh
     */
    @ApiOperation(value = "申请表延期[活动规则申请表]")
    @PostMapping("/saveOrUpdateDelay")
    @ResponseBody
    public RestResult<Long> saveOrUpdateDelay(@RequestBody ConfActivityRuleApplyRequest request) throws Throwable {
        //第一步查询主表数据，并将该条数据设置为空
        ConfActivityRule confActivityRule = new ConfActivityRule();
        confActivityRule.setDeleteFlag(1);
        confActivityRule.setId(request.getId());
        service.updateByPrimaryKeySelective(confActivityRule);//修改主表状态逻辑删除
        //第二步插入数据至申请表
        ConfActivityRuleApply confActivityRuleApply = new ConfActivityRuleApply();
        BeanUtils.copyProperties(request, confActivityRuleApply);
        confActivityRuleApply.setId(null);
        confActivityRuleApply.setDelayApplierId(request.getAdminOperate().getOperator());//延期申请人
        confActivityRuleApply.setDelayApplierReason(request.getDelayApplierReason());
        //confActivityRuleApply.setEndTime(request.getEndTime());
        confActivityRuleApply.setCurrentAction(1);
        long flag = serviceApply.saveOrUpdate(confActivityRuleApply);
        return RestResult.success(flag);
    }

    /**
     * 删除记录
     *
     * @param request 删除[活动规则申请表]请求参数
     * @return ConfActivityRuleApplyResponse 删除[活动规则申请表]响应参数
     * author tzc
     * @date 2020-3-11 20:54:04
     */
    @ApiOperation(value = "删除[活动规则申请表]记录")
    @PostMapping("/delete")
    @ResponseBody
    @Transactional
    public RestResult<Long> delete(@RequestBody ConfActivityRuleApplyRequest request) throws Throwable {
        ConfActivityRuleApply confActivityRuleApply = new ConfActivityRuleApply();
        BeanUtils.copyProperties(request, confActivityRuleApply);
        long flag = serviceApply.deleteByPrimaryKeyLogically(confActivityRuleApply);
        ConfActivityRule confActivityRule= new ConfActivityRule();
        BeanUtils.copyProperties(request, confActivityRule);
        //积分冻结成功，插入积分表中
        confActivityRule.setType(2);
        confActivityRule.setDescription("活动删除，可用积分回归平台");
        service.insertActiveRuleLog(confActivityRule);
        //积分冻结插入平台流水表中delete
        confActivityRule.setType(4);
        confPlatformService.insertPlatFromLog(confActivityRule);
        //把可用积分归还平台。
        confActivityRule.setAvailable(confActivityRule.getAvailable().negate());
        int i = confPlatformService.activityRuleDeductionPoints(confActivityRule);
        return RestResult.success(flag);
    }

    /**
     * 修改记录
     *
     * @param request 修改[活动规则申请表]请求参数
     * @return ConfActivityRuleApplyResponse 修改[活动规则申请表]响应参数
     * author tzc
     * @date 2020-3-11 20:54:04
     */
    @ApiOperation(value = "修改[活动规则申请表]记录")
    @PostMapping("/update")
    @ResponseBody
    public RestResult<Long> update(@RequestBody ConfActivityRuleApplyRequest request) throws Throwable {
        ConfActivityRuleApply confActivityRuleApply = new ConfActivityRuleApply();
        BeanUtils.copyProperties(request, confActivityRuleApply);
        long flag = serviceApply.updateByPrimaryKeySelective(confActivityRuleApply);
        return RestResult.success(flag);
    }

    /**
     * 单表查询详情信息
     *
     * @param request 查询[活动规则申请表]详情请求参数
     * @return ConfActivityRuleApplyResponse 查询[活动规则申请表]详情响应参数
     * author tzc
     * @date 2020-3-11 20:54:04
     */
    @PostMapping("/getByPrimaryKey")
    @ApiOperation(value = "查询[活动规则申请表]详情")
    @ResponseBody
    public RestResult<Map> getByPrimaryKey(@Validated @RequestBody ConfActivityRuleApplyRequest request) {
        log.info("查询详情请求参数入参，{}", JSONObject.toJSONString(request));
        if (request != null && request.getId() != null) {

            ConfActivityRuleApply confActivityRuleApply = new ConfActivityRuleApply();
            BeanUtils.copyProperties(request, confActivityRuleApply);
            ConfActivityRuleApply result = serviceApply.getByPrimaryKey(confActivityRuleApply);
            log.info("查询详情请求参数出参，{}", JSONObject.toJSONString(result));
            if (result == null) {
                return RestResult.error(ResponseCode.EXCEPTION, "记录不存在");
            }
           List<ConfActivityRuleDetail>  list =  service.selDetailList(result);
            ConfActivityRuleApplyResponse bo = new ConfActivityRuleApplyResponse();
            BeanUtils.copyProperties(result, bo);
            Set<Long> collect = list.stream().map(ConfActivityRuleDetail::getSceneId).collect(Collectors.toSet());
            Set<String> collects = new HashSet<>();
            collect.forEach(item->{
                collects.add(item.toString());
            });
            Map<Long, List<ConfActivityRuleDetail>> collect1 = list.stream().collect(Collectors.groupingBy(ConfActivityRuleDetail::getSceneId));
            List l = new ArrayList();
            for(Long key : collect1.keySet()){
                List<ConfActivityRuleDetail> confActivityRuleDetails = collect1.get(key);
                Map map = new HashMap<>();
                map.put("sceneId",confActivityRuleDetails.get(0).getSceneId());
                map.put("sceneName",confActivityRuleDetails.get(0).getSceneName());
                map.put("list",confActivityRuleDetails);
                l.add(map);
            }
            Map m = new HashMap();
            m.put("detailList",l);
            m.put("rule",bo);
            m.put("sceneId",collects);
            return RestResult.success(m);
        }
        log.info("查询详情请求结束");
        return RestResult.success(new HashMap());
    }

    /**
     * 分页查询
     *
     * @param request 分页查询请求参数
     * @return 分页列表
     * @throws Throwable 业务异常和系统异常
     */
    @PostMapping("/listPage")
    @ApiOperation(value = " 分页查询列表 ")
    @ResponseBody
    public RestResult<PageInfo<ConfActivityRuleApply>> listPage(@RequestBody ConfActivityRuleApplyRequest request) throws Throwable {
        ConfActivityRuleApply param = new ConfActivityRuleApply();
        BeanUtils.copyProperties(request, param);
        param.setDeleteFlag(0);
        return RestResult.success(serviceApply.listPageBySelective(param, request.getPageNum(), request.getPageSize()));
    }


    /**
     * CONF_ACTIVITY_RULE 查询列表（不分页）
     *
     * @param request 前端请求参数
     */
    @PostMapping("/listAll")
    @ApiOperation(value = "不分页查询 [活动规则申请表] ")
    @ResponseBody
    public RestResult<List<ConfActivityRuleApplyResponse>> listConfActivityRuleAllRecord(@RequestBody ConfActivityRuleApplyRequest request) throws Throwable {
        ConfActivityRuleApply param = new ConfActivityRuleApply();
        BeanUtils.copyProperties(request, param);
        param.setDeleteFlag(0);
        List<ConfActivityRuleApply> list = serviceApply.listAllRecord(param);
        List<ConfActivityRuleApplyResponse> responseList = list.stream().map(temp -> {
            ConfActivityRuleApplyResponse bo = new ConfActivityRuleApplyResponse();
            BeanUtils.copyProperties(temp, bo);
            return bo;
        }).filter(item -> item != null).collect(Collectors.toList());
        return RestResult.success(responseList);
    }

    /**
     * 审核提交
     */
    @PostMapping("/auditAubmit")
    @ResponseBody
    @Transactional(rollbackFor = {Exception.class})
    public RestResult auditAubmit(@RequestBody ConfActivityRuleApplyRequest request) throws Throwable {
        log.info("活动规则主表审核，传入数据{}",request);
        request.setAuditTime(new Date());
        ConfActivityRule param = new ConfActivityRule();
        BeanUtils.copyProperties(request,param);
        ConfActivityRuleApply paramApply = new ConfActivityRuleApply();
        BeanUtils.copyProperties(request,paramApply);
        if(request.getAuditSts() == 2) { //审核失败
            if(request.getAuditSts() == 2) { //审核失败
                // 修改 / 删除 审核失败  主表逻辑删除取消，申请表逻辑删除。
                int i = serviceApply.deleteByPrimaryKeyLogically(paramApply); //申请表逻辑删除
                if(request.getCurrentAction() != 0) {//首次新增数据
                    //主表根据 code逻辑删除
                    param.setCode(request.getCode());
                    param.setDeleteFlag(0);
                    /* param.setAuditReason(request.getAuditReason());*/
                    int i1 = service.deleteFlagActivityRule(param);
                }
            }
        }else if(request.getAuditSts() == 1){//审核成功
            if(request.getCurrentAction() == 0){//首次新增数据
                //新增审核通过
                param.setId(null);
                param.setAuditorId(request.getAdminOperate().getOperator());
                int i = service.saveOrUpdate(param); //新增至 主表
                //申请表逻辑删除
                paramApply.setDeleteFlag(1);
                int i1 = serviceApply.deleteByPrimaryKeyLogically(paramApply);
            }else if(request.getCurrentAction() == 1){//修改数据
                //修改数据 审核成功。/拿到页面数据。根据code 修改主表数据
               int i = service.updateByCode(param);
                //修改主表数据后，申请表设置为逻辑删除
                paramApply.setDeleteFlag(1);
               int i1 =  serviceApply.deleteByPrimaryKeyLogically(paramApply);
            }else{//删除数据
                //删除数据 审核成功 直接逻辑删除申请表数据
                paramApply.setDeleteFlag(1);
                int i1 =  serviceApply.deleteByPrimaryKeyLogically(paramApply);
                //积分冻结成功，插入积分表中
                param.setType(2);
                param.setDescription("活动删除，可用积分回归平台");
                service.insertActiveRuleLog(param);
                //积分冻结插入平台流水表中delete
                param.setType(4);
                confPlatformService.insertPlatFromLog(param);
                //把可用积分归还平台。
                param.setAvailable(param.getAvailable().negate());
                int i = confPlatformService.activityRuleDeductionPoints(param);
            }
        }else{//审核驳回
            serviceApply.updateByPrimaryKeySelective(paramApply);
        }
        return  RestResult.success("true");

    }


}

	
